package com.lzw.DailyAudit.service.dateAggregation_02;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hooya.fa.eu.api.feign.RemoteThirdPtService;
import com.hooya.fa.eu.biz.DailyAudit.entity.DailyAuditStatus;
import com.hooya.fa.eu.biz.DailyAudit.entity.StkOrigDataCollect;
import com.hooya.fa.eu.biz.DailyAudit.entity.dto.*;
import com.hooya.fa.eu.biz.DailyAudit.mapper.DailyAuditStatusMapper;
import com.hooya.fa.eu.biz.DailyAudit.mapper.DailyStkOrigDataCollectMapper;
import com.hooya.integrated.common.core.util.R;
import com.hooya.integrated.thirdpt.api.dto.EmailDTO;
import com.hooya.integrated.thirdpt.api.dto.EmailFileDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class CommonService {

    private final DailyStkOrigDataCollectMapper dailyStkOrigdataCollectMapper;

	private final DailyAuditStatusMapper statusMapper;

	private final RemoteThirdPtService remoteThirdPtService;

	private DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

	/**
	 * 发送简单文本邮件
	 *
	 * @param subject     邮件主题
	 * @param content     邮件内容
	 * @param toEmailList 收件人列表
	 * @return 发送结果
	 */
	public void sendTextEmail(String subject, String content, List<String> toEmailList) {
		try {
			EmailDTO emailDTO = EmailDTO.builder()
					.subject(subject)
					.content(content)
					.isHtml(false)
					.toEmailItems(toEmailList)
					.build();

			// 调用远程服务发送邮件
			R<String> result = remoteThirdPtService.sendEmail(Collections.singletonList(emailDTO));
			if (result.getData().equals("success")) {
				System.out.println("邮件发送成功");
			} else {
				System.out.println("邮件发送失败");
			}
		} catch (Exception e) {
			log.error("发送邮件失败: ", e);
		}
	}

	/**
	 * 发送HTML格式邮件
	 *
	 * @param subject     邮件主题
	 * @param content     邮件内容(HTML格式)
	 * @param toEmailList 收件人列表
	 * @return 发送结果
	 */
	public boolean sendHtmlEmail(String subject, String content, List<String> toEmailList) {
		try {
			EmailDTO emailDTO = EmailDTO.builder()
					.subject(subject)
					.content(content)
					.isHtml(true)
					.toEmailItems(toEmailList)
					.build();

			// 调用远程服务发送邮件
			R<String> result = remoteThirdPtService.sendEmail(Collections.singletonList(emailDTO));
			return result.getCode() == 200;
		} catch (Exception e) {
			log.error("发送HTML邮件失败: ", e);
			return false;
		}
	}

	/**
	 * 发送带附件的邮件
	 *
	 * @param subject     邮件主题
	 * @param content     邮件内容
	 * @param toEmailList 收件人列表
	 * @param ccEmailList 抄送人列表
	 * @param fileList    附件列表
	 * @param isHtml      是否为HTML格式
	 * @return 发送结果
	 */
	public boolean sendEmailWithAttachments(String subject, String content, List<String> toEmailList,
											List<String> ccEmailList, List<EmailFileDTO> fileList, boolean isHtml) {
		try {
			EmailDTO emailDTO = EmailDTO.builder()
					.subject(subject)
					.content(content)
					.isHtml(isHtml)
					.toEmailItems(toEmailList)
					.ccEmailItems(ccEmailList)
					.fileList(fileList)
					.build();

			// 调用远程服务发送邮件
			R<String> result = remoteThirdPtService.sendEmail(Collections.singletonList(emailDTO));
			return result.getCode() == 200;
		} catch (Exception e) {
			log.error("发送带附件邮件失败: ", e);
			return false;
		}
	}


	/**
	 * 修改方法的执行状态
	 * @param dailyAuditStatus 状态对象
	 * @param name 状态名称
	 * @param start 日期
	 */
	public void UpdateOrInsertStatus(DailyAuditStatus dailyAuditStatus, String name, String start){
		if (dailyAuditStatus != null) {
			statusMapper.updateStatus(name, 1, start);
		} else {
			statusMapper.insertStatus(name, 1, start);
		}
	}

    /**
     * 拼接目录
     *
     * @param dir      目录
     * @param startDate 开始日期
     * @return 拼接后的目录 - 结果为：dir/2025/08/01
     */
    public String joinDate(String dir,String startDate){
        // 计算结束日期
        String[] split = startDate.split("-");
        if (split.length != 3) {
            log.error("日期格式有误！");
            return "";
        }
        String year = split[0];
        String month = split[1];
        String day = split[2];

        return dir + "/" + year + "/" + month + "/" + day;
    }

    /**
     * 读取CSV利润报表文件数据
     *
     * @param start 读取那一天的报表
     * @return 数据列表
     */
    public List<ProfitCheckDTO> readCsvDataFromProfitCheck(String start, String company) {

        String currDate = start.replace("-", ""); //20250801  拿月和日拼接
        //  读取目录
        String dir = joinDate("./profit_check", start);
        //  读取文件
        String filePath = dir + "/" + company + "_" + currDate + ".csv";

        // 如果读取出错多半意味着 - 路径有问题了
        List<ProfitCheckDTO> dataList = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(filePath)), "GBK"))) {
            String line;
            String[] headers = null;
            int lineCount = 0;

            while ((line = br.readLine()) != null) {
                String[] values = line.split(",");

                // 第一行是标题
                if (lineCount == 0) {
                    headers = values;
                    lineCount++;
                    continue;
                }

                // 创建一个Map来存储标题和值的对应关系
                Map<String, String> rowMap = new HashMap<>();
                for (int i = 0; i < headers.length && i < values.length; i++) {
                    rowMap.put(headers[i].trim(), values[i].trim());
                }

                ProfitCheckDTO dto = new ProfitCheckDTO();
                // 填充DTO字段
                dto.setSku(rowMap.get("SKU"));
                dto.setInvoiceNumber(rowMap.get("invoice_number"));
                dto.setInvoiceDate(rowMap.get("invoice_date"));
                dto.setInboundDate(rowMap.get("inbound_date"));

                // 处理数值字段
                dto.setBeginOfMonthStock(parseIntValue(rowMap.get("begin_of_the_month_stock")));
                dto.setEndOfMonthStock(parseIntValue(rowMap.get("end_of_the_month_stock")));
                dto.setInbound(parseIntValue(rowMap.get("inbound")));
                dto.setSales(parseIntValue(rowMap.get("sales")));
                dto.setTransfer(parseIntValue(rowMap.get("transfer")));
                dto.setLost(parseIntValue(rowMap.get("lost")));
                dto.setRestock(parseIntValue(rowMap.get("restock")));

                dto.setInPriceEur(parseDoubleValue(rowMap.get("in_price_eur")));
                dto.setInPriceUsd(parseDoubleValue(rowMap.get("in_price_usd")));
                dto.setCurrencyRate(parseDoubleValue(rowMap.get("currency_rate")));
                dto.setPln(parseDoubleValue(rowMap.get("PLN")));
                dto.setType(rowMap.get("type"));
                dto.setFlag(rowMap.get("flag"));
                dto.setCompany(rowMap.get("company"));

                dataList.add(dto);
                lineCount++;
            }
        } catch (IOException e) {
            log.error("读取CSV文件时出错: {}", filePath, e);
        }

        return dataList;
    }

	/**
	 * 读取CSV文件根据文件路径
	 * @param start
	 * @param company
	 * @return
	 */
	public List<ProfitCheckDTO> readCsvByFilePath(String FilePath) {

		// 如果读取出错多半意味着 - 路径有问题了
		List<ProfitCheckDTO> dataList = new ArrayList<>();
		try (BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(Paths.get(FilePath)), "GBK"))) {
			String line;
			String[] headers = null;
			int lineCount = 0;

			while ((line = br.readLine()) != null) {
				String[] values = line.split(",");

				// 第一行是标题
				if (lineCount == 0) {
					headers = values;
					lineCount++;
					continue;
				}

				// 创建一个Map来存储标题和值的对应关系
				Map<String, String> rowMap = new HashMap<>();
				for (int i = 0; i < headers.length && i < values.length; i++) {
					rowMap.put(headers[i].trim(), values[i].trim());
				}

				ProfitCheckDTO dto = new ProfitCheckDTO();
				// 填充DTO字段
				dto.setSku(rowMap.get("SKU"));
				dto.setInvoiceNumber(rowMap.get("invoice_number"));
				dto.setInvoiceDate(rowMap.get("invoice_date"));
				dto.setInboundDate(rowMap.get("inbound_date"));

				// 处理数值字段
				dto.setBeginOfMonthStock(parseIntValue(rowMap.get("begin_of_the_month_stock")));
				dto.setEndOfMonthStock(parseIntValue(rowMap.get("end_of_the_month_stock")));
				dto.setInbound(parseIntValue(rowMap.get("inbound")));
				dto.setSales(parseIntValue(rowMap.get("sales")));
				dto.setTransfer(parseIntValue(rowMap.get("transfer_y")));
				dto.setTransfer_x(parseIntValue(rowMap.get("transfer")));
				dto.setLost(parseIntValue(rowMap.get("lost")));
				dto.setRestock(parseIntValue(rowMap.get("restock")));

				dto.setInPriceEur(parseDoubleValue(rowMap.get("in_price_eur")));
				dto.setInPriceUsd(parseDoubleValue(rowMap.get("in_price_usd")));
				dto.setCurrencyRate(parseDoubleValue(rowMap.get("currency_rate")));
				dto.setPln(parseDoubleValue(rowMap.get("PLN")));
				dto.setType(rowMap.get("type"));
				dto.setFlag(rowMap.get("flag"));
				dto.setCompany(rowMap.get("company"));

				dataList.add(dto);
				lineCount++;
			}
		} catch (IOException e) {
			log.error("读取CSV文件时出错: {}", FilePath, e);
		}

		return dataList;
	}

    /**
     * 安全地解析整数值
     */
    public Integer parseIntValue(String value) {
        if (value == null || value.isEmpty() || "None".equals(value) || "null".equals(value)) {
            return null;
        }
        try {
            // 使用cleanString方法清理字符串
            value = cleanString(value);
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
			if (value == null || value.isEmpty() || "None".equals(value) || "null".equals(value)) {
				return null;
			}
			try {
				// 使用cleanString方法清理字符串
				value = cleanString(value);
				return (int) Double.parseDouble(value);
			} catch (NumberFormatException ea) {
				log.warn("解析Integer值时出错: {}，原始字符串: '{}'", ea.getMessage(), value);
				return null;
			}
        }
    }

    /**
     * 安全地解析Double值
     */
    public Double parseDoubleValue(String value) {
        if (value == null || value.isEmpty() || "None".equals(value) || "null".equals(value)) {
            return null;
        }
        try {
            // 使用cleanString方法清理字符串
            value = cleanString(value);
            return Double.parseDouble(value);
        } catch (NumberFormatException e) {
            log.warn("解析Double值时出错: {}，原始字符串: '{}'", e.getMessage(), value);
            return null;
        }
    }

    /**
     * 清理字符串，移除各种不可见字符和引号
     *
     * @param str 需要清理的字符串
     * @return 清理后的字符串
     */
    public String cleanString(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        // 移除前后的空格和各种引号，以及不可见字符
        return str.trim().replaceAll("^[\"'\\u00AB\\u00BB\\u201C\\u201D\\u201E\\u201F\\u2039\\u203A]+", "")  // 移除开头的引号
                .replaceAll("[\"'\\u00AB\\u00BB\\u201C\\u201D\\u201E\\u201F\\u2039\\u203A]+$", "")  // 移除结尾的引号
                .replaceAll("[\\s\\u00A0\\u2000-\\u200F\\u2028-\\u202F\\u205F-\\u206F\\u3000\\uFEFF]+", "")// 移除各种空格和不可见字符
                .replaceAll("'", ""); //去除中间的单引号
    }

    /**
     * 获取前一个日期
     */
    public String getPrevDate(String dateString) {
        try {
			if(StrUtil.isBlank(dateString)){
				return "";
			}
            LocalDate date = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate prev = date.minusDays(1);
            return prev.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        } catch (Exception e) {
            log.error("日期解析错误: {}", dateString, e);
            return dateString;
        }
    }

    /**
     * 创建目录
     *
     * @param dirPath 目录路径
     */
    public void createDirectories(String dirPath) {
        try {
            Path path = Paths.get(dirPath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
                log.info("目录创建成功");
            }
        } catch (IOException e) {
            log.error("创建目录失败: {}", dirPath, e);
            throw new RuntimeException("创建目录失败: " + dirPath, e);
        }
    }

    //数据校验部分
    public void dataVerificationB2b(List<B2bDataDTO> data) {
        // 检查每个cpbh组中的price值是否唯一
        Map<String, Set<BigDecimal>> priceCountByCpbh = new HashMap<>();

        for (B2bDataDTO item : data) {
            String cpbh = item.getCpbh();
            Double price = item.getPrice();

            if (cpbh != null) {
                priceCountByCpbh.computeIfAbsent(cpbh, k -> new HashSet<>());
                priceCountByCpbh.get(cpbh).add(BigDecimal.valueOf(price));
            }
        }

        // 检查是否有cpbh组中的price值不唯一
        for (Map.Entry<String, Set<BigDecimal>> entry : priceCountByCpbh.entrySet()) {
            Set<BigDecimal> prices = entry.getValue();
            // 如果一个cpbh组中有多个不同的price值（不包括null），或者有一个price值和一个null值
            if (prices.size() > 1 || (prices.size() == 1 && prices.contains(null))) {
                throw new RuntimeException("每个cpbh组中的price值应该唯一，但cpbh: " + entry.getKey() + " 有多个不同的price值");
            }
        }

        // 检查是否有价格为空的数据
        List<B2bDataDTO> noPriceData = data.stream().filter(item -> item.getPrice() == null).collect(Collectors.toList());

        if (!noPriceData.isEmpty()) {
            throw new RuntimeException("存在没有价格的数据，数量: " + noPriceData.size());
        }

        log.info("数据验证通过");
    }

    public void dataVerificationB2c(List<B2cDataDTO> data) {
        List<B2cDataDTO> noPriceData = data.stream()
                .filter(dto -> (dto.getFromcompany() != null && (dto.getFromcompany().startsWith("costway") || dto.getFromcompany().startsWith("fds")))
                        && dto.getPrice() == null
                        && dto.getBelongs() != null && dto.getBelongs().startsWith("costway"))
                .collect(Collectors.toList());

        if (!noPriceData.isEmpty()) {
            log.error("存在没有价格数据，数量: {} 数据为：{}", noPriceData.size(), noPriceData);
            throw new RuntimeException("存在没有价格的数据，数量: " + noPriceData.size());
        }

        log.info("数据验证通过");
    }

    public void dataVerificationBs(List<BsDataDTO> data) {
        List<BsDataDTO> noPriceData = data.stream().filter(dto -> dto.getPrice() == null && dto.getBelongs() != null && dto.getBelongs().startsWith("costway")).collect(Collectors.toList());

        if (!noPriceData.isEmpty()) {
            log.error("Bs的异常数据数量为：{} ， 异常数据为：{}", noPriceData.size(), noPriceData);
            throw new RuntimeException("存在没有价格的数据，数量: " + noPriceData.size());
        }
        log.info("数据验证通过");
    }

    public void dataVerificationCg(List<CGDataDTO> data) {
        // 验证逻辑：检查是否存在没有价格的记录
        List<CGDataDTO> noPriceCount = data.stream()
                .filter(d -> d.getPrice() == null)
                .collect(Collectors.toList());

        if (!noPriceCount.isEmpty()) {
            log.error("异常数据数量为：{}，异常数据为：{}", noPriceCount.size(), noPriceCount);
            throw new RuntimeException("存在没有价格或价格为零的记录，数量: " + noPriceCount);
        }
    }

    public void dataVerificationTh(List<ThDataDTO> data) {
        List<ThDataDTO> noPriceData = data.stream()
                .filter(d -> d.getPrice() == null)
                .collect(Collectors.toList());

        if (!noPriceData.isEmpty()) {
            log.error("存在无价格的数据，数量：{} , 数据{}", noPriceData.size(), noPriceData);
            throw new RuntimeException("存在无价格的数据");
        }
    }

    public void dataVerificationZy(List<ZyDataDTO> data) {
        // 验证逻辑：检查是否存在没有价格的记录
        List<ZyDataDTO> noPriceCount = data.stream()
                .filter(d -> d.getPrice() == null)
                .collect(Collectors.toList());

        if (!noPriceCount.isEmpty()) {
            log.error("存在没有价格的记录，数量: {} , 数据{}", noPriceCount.size(), noPriceCount);
            throw new RuntimeException("存在没有价格的记录，数量: " + noPriceCount);
        }
    }

    /**
     * 批量插入数据 - Stk
     */
    public void batchInsert(List<StkOrigDataCollect> records) {
        if (records.isEmpty()) {
            log.info("批量插入数据为空");
            return;
        }
        try {
            // 将大数据集分批处理
            int batchSize = 5000; // 每批处理5000条记录
            for (int i = 0; i < records.size(); i += batchSize) {
                int endIndex = Math.min(i + batchSize, records.size());
                List<StkOrigDataCollect> batch = records.subList(i, endIndex);
                dailyStkOrigdataCollectMapper.insertBatch(batch);
            }
            log.info("批量插入数据完成，插入条数：{}", records.size());
        } catch (Exception e) {
            log.error("批量插入数据失败", e);
            throw new RuntimeException("批量插入数据失败", e);
        }
    }

    // 数据转换方法部分
    public List<StkOrigDataCollect> convertB2bToStkOrigDataCollect(List<B2bDataDTO> dataList) {
        return dataList.stream().map(dto -> {
            StkOrigDataCollect record = convertBaseStkOrignDataCollect(dto.getCpbh(), dto.getSl(), dto.getDate(), dto.getPlace());
            record.setSeller(dto.getSeller());
            record.setBuyer(dto.getBuyer());
            record.setFromcountry(dto.getFromcountry());
            record.setTocountry(dto.getTocountry());
            record.setSheetnumber(dto.getSheetnumber());
            record.setType(dto.getType());
            record.setSellertaxid(dto.getSellertaxid());
            record.setBuyertaxid(dto.getBuyertaxid());
            record.setPrice(dto.getPrice() == null ? 0.0 : dto.getPrice());
            record.setOceanfee(dto.getOceanfee() == null ? 0.0 : dto.getOceanfee());
            record.setCurrency(dto.getCurrency());
            record.setInvoiceid(dto.get_id());
            record.setBelongs(dto.getBelongs());
            record.setDirection(dto.getDirection());
            record.setInvoicedate(dto.getInvoicedate());
            record.setExportprice(dto.getExportprice() == null ? 0.0 : dto.getExportprice());
            record.setInvoiceno(dto.getInvoiceno());
            record.setCreatetime(LocalDateTime.now().format(df));
            return record;
        }).collect(Collectors.toList());
    }

    public List<StkOrigDataCollect> convertB2cToStkOrigDataCollect(List<B2cDataDTO> dataList, boolean hasPrice) {

        return dataList.stream().map(dto -> {
            StkOrigDataCollect record = convertBaseStkOrignDataCollect(dto.getCpbh(), dto.getSl(), dto.getDate(), dto.getPlace());
            record.setDirection(dto.getDirection());
            record.setBelongs(dto.getBelongs());
            record.setType(dto.getType());
            record.setSeller(dto.getFromcompany());
            record.setOrderid(dto.getOrderid());
            record.setSheetnumber(dto.getSheetnumber());
            record.setInvoicedate(dto.getInvoicedate());
            if (hasPrice) {
                record.setPrice(dto.getPrice() == null ? 0.0 : dto.getPrice());
                record.setCurrency(dto.getCurrency());
                record.setInvoiceno(dto.getHthm());
            }
            record.setBuyer(dto.getTocompany());
            record.setCreatetime(LocalDateTime.now().format(df));
            return record;
        }).collect(Collectors.toList());
    }

    public List<StkOrigDataCollect> convertBsToStkOrigDataCollect(List<BsDataDTO> dataList, boolean hasPrice) {
        return dataList.stream().map(dto -> {
            StkOrigDataCollect record = convertBaseStkOrignDataCollect(dto.getCpbh(), dto.getSl(), dto.getDate(), dto.getPlace());
            record.setDirection(dto.getDirection());
            record.setBelongs(dto.getBelongs());
            record.setType(dto.getType());
            if (hasPrice) {
                record.setInvoicedate(dto.getInvoicedate());
                record.setCurrency(dto.getCurrency());
                record.setPrice(dto.getPrice() == null ? 0.0 : dto.getPrice());
            }
            record.setCreatetime(LocalDateTime.now().format(df));
            return record;
        }).collect(Collectors.toList());
    }

    public List<StkOrigDataCollect> convertGgToStkOrigDataCollect(List<CGDataDTO> dataList) {
        List<StkOrigDataCollect> result = new ArrayList<>();
        for (CGDataDTO data : dataList) {
            StkOrigDataCollect record = new StkOrigDataCollect();
            convertStkOrignDataCollect(record, data.getCpbh(), data.getHthm(), data.getSl(), data.getDate(), data.getPlace(), data.getDirection(), data.getBelongs());
            record.setSheetnumber(data.getSheetnumber());
            record.setType(data.getType());
            record.setInvoicedate(data.getInvoicedate());
            record.setPrice(data.getPrice() == null ? 0.0 : data.getPrice());
            record.setCurrency(data.getCurrency());
            record.setCreatetime(LocalDateTime.now().format(df));
            result.add(record);
        }
        return result;
    }

    public List<StkOrigDataCollect> convertThToStkOrigDataCollect(List<ThDataDTO> dataList) {
        List<StkOrigDataCollect> result = new ArrayList<>();
        for (ThDataDTO data : dataList) {
            StkOrigDataCollect record = new StkOrigDataCollect();
            BeanUtil.copyProperties(data, record);
            convertStkOrignDataCollect(record, data.getCpbh(), data.getHthm(), data.getSl(), data.getDate(), data.getPlace(), data.getDirection(), data.getBelongs());
            record.setType(data.getType());
            record.setSeller(data.getFromcompany());
            record.setBuyer(data.getTocompany());
            record.setFromcountry(data.getFromcountry());
            record.setTocountry(data.getTocountry());
            record.setSheetnumber(data.getSheetnumber());
            record.setInvoiceno(data.getHthm());
            record.setOceanfee(data.getOceanfee() != null ? data.getOceanfee() : 0);
            record.setInvoiceid(data.get_id());
            record.setInvoicedate(String.valueOf(data.getInvoicedate()));
            record.setCurrency(data.getCurrency());
            record.setPrice(data.getPrice() != null ? data.getPrice() : 0);
            record.setExportprice(data.getExportprice() != null ? data.getExportprice() : 0);
            record.setCreatetime(LocalDateTime.now().format(df));
            result.add(record);
        }
        return result;
    }

    public List<StkOrigDataCollect> convertZyToStkOrigDataCollect(List<ZyDataDTO> dataList) {
        List<StkOrigDataCollect> result = new ArrayList<>();
        for (ZyDataDTO data : dataList) {
            StkOrigDataCollect record = new StkOrigDataCollect();
            BeanUtil.copyProperties(data, record);
            convertStkOrignDataCollect(record, data.getCpbh(), data.getHthm(), data.getSl(), data.getDate(), data.getPlace(), data.getDirection(), data.getBelongs());
            record.setType(data.getType());
            record.setSeller(data.getFromcompany());
            record.setBuyer(data.getTocompany());
            record.setFromcountry(data.getFromcountry());
            record.setTocountry(data.getTocountry());
            record.setSheetnumber(data.getSheetnumber());
            record.setInvoiceno(data.getHthm());
            record.setOceanfee(data.getOceanfee() != null ? data.getOceanfee() : 0);
            record.setInvoiceid(data.get_id());
            record.setInvoicedate(String.valueOf(data.getInvoicedate()));
            record.setCurrency(data.getCurrency());
            record.setPrice(data.getPrice() != null ? data.getPrice() : 0);
            record.setExportprice(data.getExportprice() != null ? data.getExportprice() : 0);
            record.setCreatetime(LocalDateTime.now().format(df));
            result.add(record);
        }
        return result;
    }

    /**
     * 提取方法的公共部分--基础转换
     */
    private StkOrigDataCollect convertBaseStkOrignDataCollect(String cpbh, Integer sl, String date, String place) {
        StkOrigDataCollect record = new StkOrigDataCollect();
        record.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase().toLowerCase());
        record.setSku(cpbh);
        record.setQty(sl);
        record.setInoutdate(date);
        record.setWhid(place);
        return record;
    }

    private void convertStkOrignDataCollect(StkOrigDataCollect record, String cpbh, String hthm, Integer sl, String date, String place, String direction, String belongs) {
        record.setId(UUID.randomUUID().toString().replace("-", "").toLowerCase());
        record.setSku(cpbh);
        record.setInvoiceno(hthm);
        record.setQty(sl);
        record.setInoutdate(date);
        record.setWhid(place);
        record.setDirection(direction);
        record.setBelongs(belongs);
    }


}
